package cn.hinglo.gameclaw.im.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @createTime: 2018/3/6
 * @author: HingLo
 * @description: 网易云的网络请求
 */
public class HttpClientUtils {
    /**
     * 定义成功的响应码
     */
    private static final int RES_CODE = 200;

    private static final String APP_KEY = "55ce1c2039f6342382a99aa3e3d47f80";
    private static final String APP_SECRET = "91581c6ea371";

    private static Map<String, String> HEADER = new HashMap<>();


    static {
        HEADER.put("AppKey", APP_KEY);
    }


    public static String postFormData(String url, Map<String, Object> params, Boolean bool) {
        String nonce = RandomUtil.randomNumbers(10);
        String curTime = String.valueOf(System.currentTimeMillis());
        curTime = StrUtil.subPre(curTime, 10);
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, nonce, curTime);
        HEADER.put("Nonce", nonce);
        HEADER.put("CurTime", curTime);
        HEADER.put("CheckSum", checkSum);

        //设置请求的URL
        HttpRequest httpRequest = HttpRequest.post(url);
        if (bool) {
            HEADER.put("Content-Type", "application/json;charset=utf-8");
            if (params != null) {
                httpRequest.body(JSONUtil.toJsonStr(params));
            }
        } else {
            HEADER.put("Content-Type", "application/x-www-form-urlencoded");
            //添加参数
            if (params != null) {
                httpRequest.form(params);
            }
        }
        //添加Header
        if (HEADER != null) {
            for (Map.Entry<String, String> entry : HEADER.entrySet()) {
                httpRequest.header(entry.getKey(), entry.getValue());
            }
        }
        //执行请求
        HttpResponse httpResponse = httpRequest.execute();
        return httpResponse.body();

    }


    /**
     * 获取响应结果码
     *
     * @param result Json结果集
     * @return 返回响应吗
     */
    public static boolean getCode(String result) {
        JSON json = JSONUtil.parse(result);
        return RES_CODE == Convert.toInt(json.getByExp("code"));
    }

    /**
     * 从json格式数据中返回指定的名称的值
     *
     * @param result json格式的结果集
     * @param key    返回的key
     * @return 返回指定key的值
     */
    public static <T> T getResult(String result, String key) {
        JSON json = JSONUtil.parse(result);
        return (T) json.getByExp(key);
    }


}
